package com.example.CollaborativeDiscussionLearning.utils;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;
import java.io.IOException;
import java.util.Base64;

public class PdfBase64ImgReplacedElementFactory implements ReplacedElementFactory {
    /**
     * * 实现createReplacedElement 替换html中的Img标签
     * *
     * * @param c 上下文
     * * @param box 盒子
     * * @param uac 回调
     * * @param cssWidth css宽
     * * @param cssHeight css高
     * * @return ReplacedElement
     */
    @Override
    public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
        //遍历所有标签
        Element e= box.getElement();
        if(e==null){
            return null;
        }
        String nodeName=e.getNodeName();
        //找到所有img标签
        if(nodeName.equals("img")){
            String attribute=e.getAttribute("src");
            FSImage fsImage;
            try{
                //生成itext图像
                fsImage=buildImage(attribute,uac);
            } catch (BadElementException | IOException ex) {
               fsImage=null;
            }
            if(fsImage!=null){
                //对图像缩放
                if(cssWidth!=-1||cssHeight!=-1){
                    fsImage.scale(cssWidth,cssHeight);
                }
                return new ITextImageElement(fsImage);
            }
        }
        return null;
    }

    /*编解码base64并生成itext图像*/
    protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException, BadElementException {
        FSImage fiImage;
        //图片的src要为src="data:image/jpg;base64,{图片的base64code}"这种base64格式
        if(srcAttr.toLowerCase().startsWith("data:image/")){
            String base64Code=srcAttr.substring(srcAttr.indexOf("base64,")+"base64,".length());
            //解码
            byte[] decodeBytes= Base64.getDecoder().decode(base64Code);
            fiImage=new ITextFSImage(Image.getInstance(decodeBytes));
        }else{
            fiImage=uac.getImageResource(srcAttr).getImage();
        }
        return fiImage;
    }

    @Override
    public void reset() {

    }
    @Override
    public void remove(Element element) {

    }
    @Override
    public void setFormSubmissionListener(FormSubmissionListener formSubmissionListener) {
    }
}
